import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import 'package:ecy_app_flutter/routes/consignment/model/ConsignProduct.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:waterfall_flow/waterfall_flow.dart';

import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../ecycommon/utils/EcyLogger.dart';
import '../../ecycommon/utils/EcyUserUtil.dart';
import '../../model/EcyApiCommonPage.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../../model/SysDictData.dart';

class EcyConsignmentListPage extends StatefulWidget {
  late _EcyConsignmentListPageState state;
  late String status;
  late bool currentUserFlag;
  late List<dynamic> consignmentList;

  EcyConsignmentListPage(this.status, this.currentUserFlag, {required super.key});

  @override
  State<StatefulWidget> createState() {
    state = _EcyConsignmentListPageState();
    return state;
  }

  reloadData(String search) {
    state._refreshData(search);
  }

}

class _EcyConsignmentListPageState extends State<EcyConsignmentListPage> {

  _EcyConsignmentListPageState();

  int _total = 0;
  int _currentPage = 1;
  bool _hasMore = false;
  
  final List<int> indexList = List.filled(19, 0);
  final List<ConsignProduct> _consignProductList = [];

  List<SysDictData> feedbackCategoryList = [];
  final RefreshController _refreshController = RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();

    _loadFeedbackCategory();

    _refreshData("");
  }

  Future<void> _loadFeedbackCategory() async {
    try {
      var response = await EcyRequestbasemanager()
          .get("/system/dict/data/type/feed_back_category", {});
      if (response != null) {
        var commonResponse =
        EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          setState(() {
            feedbackCategoryList = ((response["data"] ?? []) as List<dynamic>)
                .map((e) => SysDictData.fromJson(e as Map<String, dynamic>))
                .toList();
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取反馈字典失败$e");
    }
  }

  //下拉刷新
  Future<void> _onRefresh() async {
    _currentPage = 1;
    await _refreshData("", page: _currentPage);
    _refreshController.refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshController.loadComplete();
    } else {
      _refreshController.loadNoData();
    }
  }

  //上拉加载更多
  Future<void> _onLoading() async {
    if (_hasMore) {
      _currentPage++;
      await _refreshData("", page: _currentPage);
      _refreshController.loadComplete();
    } else {
      _refreshController.loadNoData();
    }
  }

  Future<void> _refreshData(String search, {int page = 1}) async {
    try {
      Map<String, dynamic> body = {
        "size": 12,
        "current": page,
        "title": search,
        "status": "1",
        "currentUserFlag": widget.currentUserFlag,
      };
      var response = await EcyRequestbasemanager()
          .post("/app/api/app/consign/page", body);
      if (response != null) {
        var commonResponse =
        EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<ConsignProduct> commonPage =
          EcyApiCommonPage.fromJson(
              response["data"], (json) => ConsignProduct.fromJson(json));
          _total = commonPage.pages ?? 0;
          _currentPage = commonPage.current ?? 0;
          var consignProductList = commonPage.records ?? [];
          if (page == 1) {
            _consignProductList.clear();
          }
          setState(() {
            _consignProductList.addAll(consignProductList);
            _hasMore = _total > _currentPage;
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取失败$e");
    }
  }

  Future<void> _onLike(ConsignProduct consignProduct) async {
    try {
      var loginFlag = await EcyUserUtil.logined();
      if (loginFlag) {
        var likeFlag = !(consignProduct.like ?? false);
        consignProduct.likeCount =
            (consignProduct.likeCount ?? 0) + (likeFlag ? 1 : -1);
        setState(() {
          consignProduct.like = likeFlag;
        });

        Map<String, dynamic> body = {
          "productId": consignProduct.productId,
          "type": 0,
          "like": likeFlag
        };
        var response = await EcyRequestbasemanager()
            .post("/app/api/app/consign/like", body);
        if (response != null) {
          var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
          if (commonResponse.code != 0 && commonResponse.code != 200) {
            EasyLoading.showToast("请稍后再试",
                duration: const Duration(seconds: 2));
          }
        }
      } else {
        EasyLoading.showToast("请先登录", duration: const Duration(seconds: 1));
      }
    } catch (e) {
      EcyLogger.log("点赞失败$e");
    }
  }

  Future<void> _feedback(ConsignProduct consignProduct,
      List<String> contentFeedbackCodes, String uninterestedCode) async {
    try {
      var currUser = await EcyUserUtil.getLoginedUserInfo2();
      if (currUser.token.isEmpty) {
        EasyLoading.showToast("请先登录", duration: const Duration(seconds: 2));
        return;
      }

      Map<String, dynamic> body = {
        "postId": consignProduct.productId,
        "postUserId": consignProduct.userId,
        "userId": currUser.uid,
        "type": "1",
        "contentFeedbackCode": contentFeedbackCodes,
        "uninterestedCode": uninterestedCode,
      };
      var response = await EcyRequestbasemanager()
          .post("/app/api/app/valley/circle/feedback", body);
      if (response != null) {
        var commonResponse =
        EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EasyLoading.showToast("已反馈，将减少该内容",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EcyLogger.log("点赞失败$e");
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget image = Image.asset("assets/images/app_icon.png");

    if (_consignProductList.isEmpty) {
      return SmartRefresher(
        enablePullDown: true,
        enablePullUp: false,
        header: const ClassicHeader(
          refreshStyle: RefreshStyle.Follow,
          idleText: '下拉刷新',
          refreshingText: '加载中...',
          completeText: '刷新完成',
          failedText: '刷新失败',
          textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
          releaseText: '松开刷新',
          iconPos: IconPosition.top,
          spacing: 8,
        ),
        onRefresh: () => _onRefresh(),
        controller: _refreshController,
        child: ListView.builder(
          shrinkWrap: true,
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
          itemCount: 1,
          itemBuilder: (context, index) {
            return Column(children: [
              Image.asset('assets/images/empty/ic_empty_search.png',
                  width: 150, height: 150),
              const Text('暂无寄售',
                  style: TextStyle(fontSize: 18, color: Colors.grey)),
            ]);
          },
        ),
      );
    }

    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      physics: const BouncingScrollPhysics(),
      header: const ClassicHeader(
        refreshStyle: RefreshStyle.Follow,
        idleText: '下拉刷新',
        refreshingText: '加载中...',
        completeText: '刷新完成',
        failedText: '刷新失败',
        textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
        releaseText: '松开刷新',
        iconPos: IconPosition.top,
        spacing: 8,
      ),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus? mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = const Text("上拉加载更多",
                style: TextStyle(color: Color(0xFF8C8C8C)));
          } else if (mode == LoadStatus.loading) {
            body = const Text("加载中...",
                style: TextStyle(color: Color(0xFF8C8C8C)));
          } else if (mode == LoadStatus.failed) {
            body = const Text("加载失败，点击重试",
                style: TextStyle(color: Color(0xFF8C8C8C)));
          } else if (mode == LoadStatus.canLoading) {
            body = const Text("松手加载更多",
                style: TextStyle(color: Color(0xFF8C8C8C)));
          } else {
            body = const Text("没有更多寄售了~",
                style: TextStyle(color: Color(0xFF8C8C8C)));
          }
          return SizedBox(
            height: 35.w,
            child: Center(child: body),
          );
        },
      ),
      onRefresh: () => _onRefresh(),
      onLoading: () => _onLoading(),
      controller: _refreshController,
      child: WaterfallFlow.builder(
          physics: const AlwaysScrollableScrollPhysics(),
          gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 8.w,
            mainAxisSpacing: 8.w,
          ),
          itemCount: _consignProductList.length,
          itemBuilder: (BuildContext context, int index) {
            var consignProduct = _consignProductList[index];
            return GestureDetector(
                child:  Wrap(
                  children: [
                    Container(
                        width: (MediaQuery.of(context).size.width - 24.w) / 2,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(8.r)),
                          color: Colors.white,
                        ),
                        child: CachedNetworkImage(
                            width:
                            (MediaQuery.of(context).size.width - 24.w) /
                                2,
                            height: 176.w,
                            imageUrl: consignProduct.mainImageUrl ?? "",
                            imageBuilder: (context, imageProvider) =>
                                Container(
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.all(Radius.circular(8.r)),
                                      image: DecorationImage(
                                          image: imageProvider,
                                          fit: BoxFit.cover)),
                                ),
                            errorWidget: (context, url, error) =>
                                Image.asset("assets/images/app_icon.png"))),
                    Container(
                        width: (MediaQuery.of(context).size.width - 24.w) / 2,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(8.r),
                              bottomRight: Radius.circular(8.r)),
                          color: const Color(0xFFFFFFFF),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: const EdgeInsets.only(left: 8, top: 8),
                              child: Text(
                                consignProduct.title ?? "",
                                style: const TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w700,
                                    fontSize: 14,
                                    color: Color(0xFF262626)),
                                textAlign: TextAlign.left,
                              ),
                            ),
                            Row(
                              mainAxisAlignment:
                              MainAxisAlignment.spaceBetween,
                              children: [
                                RichText(
                                  text: TextSpan(children: [
                                    WidgetSpan(
                                      alignment: PlaceholderAlignment.middle,
                                      child: Padding(
                                        padding: const EdgeInsets.all(6),
                                        child: SizedBox(
                                          height: 20,
                                          width: 20,
                                          child: ClipRRect(
                                              borderRadius:
                                              BorderRadius.circular(50.0),
                                              child: CachedNetworkImage(
                                                width: 20.w,
                                                height: 20.w,
                                                imageUrl: consignProduct
                                                    .sellerAvatar ??
                                                    "",
                                                imageBuilder: (context,
                                                    imageProvider) =>
                                                    Container(
                                                      decoration: BoxDecoration(
                                                          image: DecorationImage(
                                                              image:
                                                              imageProvider,
                                                              fit: BoxFit.cover)),
                                                    ),
                                                placeholder: (context, url) =>
                                                image,
                                                errorWidget:
                                                    (context, url, error) =>
                                                image,
                                              )),
                                        ),
                                      ),
                                    ),
                                    TextSpan(
                                        text: ' ${consignProduct.sellerName}',
                                        style: const TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w500,
                                            fontSize: 12,
                                            color: Color(0xFF8C8C8C))),
                                  ]),
                                ),
                                GestureDetector(
                                  behavior: HitTestBehavior.translucent,
                                  child: Padding(
                                      padding: const EdgeInsets.all(6),
                                      child: RichText(
                                        text: TextSpan(
                                          children: [
                                            (consignProduct.like ?? false
                                                ? WidgetSpan(
                                              alignment:
                                              PlaceholderAlignment
                                                  .middle,
                                              child: Image.asset(
                                                "assets/images/ic_heart_checked.png",
                                                scale: 2.5,
                                              ),
                                            )
                                                : WidgetSpan(
                                              alignment:
                                              PlaceholderAlignment
                                                  .middle,
                                              child: Image.asset(
                                                  "assets/images/ic_heart_unchecked.png",
                                                  scale: 2.5),
                                            )),
                                            TextSpan(
                                                text:
                                                ' ${consignProduct.likeCount ?? 0}',
                                                style: const TextStyle(
                                                    fontFamily: "PingFang SC",
                                                    fontWeight:
                                                    FontWeight.w500,
                                                    fontSize: 12,
                                                    color:
                                                    Color(0xFF8C8C8C))),
                                          ],
                                        ),
                                      )),
                                  onTap: () {
                                    _onLike(consignProduct);
                                  },
                                ),
                              ],
                            ),
                          ],
                        )),
                  ],
                ),
                onTap: () {
                  EcyRouter().pushWithCallBack(
                      context,
                      EcyRouter.consignmentDetailPage,
                      {"productId": consignProduct.productId}, (newValue) {
                    if (newValue != null) {
                      _refreshData("", page: 1);
                    }
                  });
                },onLongPress: () => _showMyDialog(context, consignProduct));
          }),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
  }

  @override
  void deactivate() {
    super.deactivate();
  }

  // 用户动态反馈功能
  void _showMyDialog(BuildContext context, ConsignProduct consignProduct) {
    var feedBack1List =
    feedbackCategoryList.where((n) => n.remark == "0").toList();
    var feedBack2List =
    feedbackCategoryList.where((n) => n.remark == "1").toList();

    showGeneralDialog(
      context: context,
      barrierDismissible: true,
      barrierLabel: "TransparentImageDialog",
      transitionDuration: const Duration(milliseconds: 300),
      pageBuilder: (context, animation, secondaryAnimation) {
        return Center(
          child: Material(
            color: Colors.transparent,
            child: Container(
              width: 330.w,
              height: 290.w,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(8.r)),
                // image: const DecorationImage(
                //   image: AssetImage(
                //     "assets/images/Rectangle_208.png",
                //   ),
                // ),
              ),
              child: Column(
                children: [
                  const Padding(padding: EdgeInsets.fromLTRB(0, 21, 0, 0)),
                  Row(
                    children: [
                      const Padding(
                          padding: EdgeInsets.fromLTRB(17, 0, 0, 0)),
                      Image.asset(
                        'assets/images/uninteresting.png',
                        width: 14.w,
                      ),
                      const Padding(
                          padding: EdgeInsets.fromLTRB(5, 0, 0, 0)),
                      const Text(
                        '不感兴趣',
                        style: TextStyle(
                          color: Color(0xFF262626),
                          fontFamily: "PingFang SC",
                          fontSize: 14,
                        ),
                      ),
                      const Padding(
                          padding: EdgeInsets.fromLTRB(8, 0, 0, 0)),
                      const Text(
                        '将减少此类内容推荐',
                        style: TextStyle(
                          color: Color(0xFF8c8c8c),
                          fontFamily: "PingFang SC",
                          fontSize: 10,
                        ),
                      ),
                    ],
                  ),
                  const Padding(padding: EdgeInsets.only(bottom: 10)),
                  Wrap(
                    spacing: 10.0,
                    runSpacing: 15.0,
                    alignment: WrapAlignment.center,
                    children: feedBack1List.map((feedBack) {
                      return GestureDetector(
                        child: Padding(
                          padding:
                          const EdgeInsets.symmetric(horizontal: 12),
                          child: Container(
                            alignment: Alignment.center,
                            width: 120.w,
                            height: 34.w,
                            margin: EdgeInsets.zero,
                            padding: EdgeInsets.zero,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4),
                                color: const Color(0xFFF5F5F5)),
                            child: Text(
                              feedBack.dictLabel ?? "",
                              style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w400,
                                  fontSize: 12.sp,
                                  color: const Color(0xFF595959)),
                            ),
                          ),
                        ),
                        onTap: () {
                          EcyRouter.pop(context, "");
                          _feedback(consignProduct, [],
                              feedBack.dictValue.toString());
                        },
                      );
                    }).toList(),
                  ),
                  const Padding(padding: EdgeInsets.only(bottom: 10)),
                  Row(
                    children: [
                      const Padding(
                          padding: EdgeInsets.fromLTRB(17, 20, 0, 0)),
                      Image.asset(
                        'assets/images/fankui.png',
                        width: 14.w,
                      ),
                      const Padding(
                          padding: EdgeInsets.fromLTRB(5, 0, 0, 0)),
                      const Text(
                        '内容反馈',
                        style: TextStyle(
                          color: Color(0xFF262626),
                          fontFamily: "PingFang SC",
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                  const Padding(padding: EdgeInsets.only(bottom: 10)),
                  Wrap(
                    spacing: 10.0,
                    runSpacing: 15.0,
                    alignment: WrapAlignment.center,
                    children: feedBack2List.map((feedBack) {
                      return GestureDetector(
                        child: Padding(
                          padding:
                          const EdgeInsets.symmetric(horizontal: 12),
                          child: Container(
                            alignment: Alignment.center,
                            width: 120.w,
                            height: 34.w,
                            margin: EdgeInsets.zero,
                            padding: EdgeInsets.zero,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4),
                                color: const Color(0xFFF5F5F5)),
                            child: Text(
                              feedBack.dictLabel ?? "",
                              style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w400,
                                  fontSize: 12.sp,
                                  color: const Color(0xFF595959)),
                            ),
                          ),
                        ),
                        onTap: () {
                          EcyRouter.pop(context, "");
                          _feedback(consignProduct, [feedBack.dictValue.toString()], "");
                        },
                      );
                    }).toList(),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

}